package com.shengqin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shengqin.common.pojo.CommonPage;
import com.shengqin.entity.CalculateLog;
import com.shengqin.entity.Plan;
import com.shengqin.mapper.CalculateErrorLogMapper;
import com.shengqin.service.ICalculateLogService;
import com.shengqin.service.IPlanService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class CalculateLogServiceImpl extends ServiceImpl<CalculateErrorLogMapper, CalculateLog> implements ICalculateLogService {

    private final IPlanService planService;

    @Override
    public Page<CalculateLog> queryPage(CommonPage<CalculateLog> commonPage) {
        CalculateLog calculateLog = commonPage.getQueryParam();
        QueryWrapper<CalculateLog> queryWrapper = new QueryWrapper<>();
        if (calculateLog != null) {
            if (calculateLog.getFlag() != null) {
                queryWrapper.lambda().eq(CalculateLog::getFlag, calculateLog.getFlag());
            }
            if (StringUtils.hasLength(calculateLog.getReqParam())) {
                queryWrapper.lambda().like(CalculateLog::getReqParam, calculateLog.getReqParam());
            }
        }
        queryWrapper.lambda().orderByDesc(CalculateLog::getId);
        Page<CalculateLog> page = new Page<>(commonPage.getPageNo(), commonPage.getPageSize());
        this.page(page, queryWrapper);
        buildRecord(page.getRecords());
        return page;
    }

    private void buildRecord(List<CalculateLog> records) {
        Set<Integer> planIds = records.stream().map(CalculateLog::getPlanId).collect(Collectors.toSet());
        if (planIds.size() > 0) {
            List<Plan> planList = planService.listByIds(planIds);
            Map<Integer, Plan> planMap = planList.stream().collect(Collectors.toMap(Plan::getId, plan -> plan));
            for (CalculateLog record : records) {
                Plan plan = planMap.get(record.getPlanId());
                if (plan != null) {
                    record.setPlanCode(plan.getCode());
                    record.setPlanName(plan.getName());
                }
            }
        }
    }
}
